package org.chintoooor.trio.server.http.task;

import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Collection;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger;

public class HttpTaskModel {

	private final Logger logger = Logger.getLogger(HttpTaskModel.class
			.getCanonicalName());

	private final Selector selector;
	private final Collection<SocketChannel> unregisteredChannels;
	private final ReentrantLock reentrantLockForTheSelectorModel;

	public HttpTaskModel(Selector selector,
			Collection<SocketChannel> unregisteredChannels) {
		super();
		this.selector = selector;
		this.unregisteredChannels = unregisteredChannels;
		this.reentrantLockForTheSelectorModel = new ReentrantLock();
	}

	public Selector getSelector() {
		return selector;
	}

	public boolean hasUnregisteredChannels() {
		return !unregisteredChannels.isEmpty();
	}

	public void registerAll() {
		reentrantLockForTheSelectorModel.lock();
		for (SocketChannel socketChannel : unregisteredChannels) {
			try {
				logger.fine("Registering connection " + socketChannel
						+ " with " + selector);

				socketChannel.register(selector, SelectionKey.OP_READ);

				logger.fine("Registered connection " + socketChannel + " with "
						+ selector);

			} catch (ClosedChannelException e) {
				logger.warning(e.getMessage());
			}
		}
		unregisteredChannels.clear();
		reentrantLockForTheSelectorModel.unlock();
	}

	public void submit(SocketChannel socketChannel) {
		reentrantLockForTheSelectorModel.lock();
		unregisteredChannels.add(socketChannel);
		reentrantLockForTheSelectorModel.unlock();
		logger.fine("Submitted channel, waiting for registration with selector "
				+ socketChannel);
	}
}
